<template>
    <div>
        <global-tables
            @handleAllSelect="handleAllSelect"
            @changePage="handleChangePage"
            :list="list"
            :total="total"
            :loading="loading"
            :columns="columns"
            :current="search.Page"
        >
            <Form :model="search" :label-width="80">
                <div class="table-top-wrap">
                    <div>
                        <div>
                            <Button v-if="isAddBtn" class="features-btn" @click="handleBtnClick(null,'add')">
                                <Icon type="md-add" size="18"/>新建
                            </Button>
                            <Button v-if="isDelete" class="features-btn btn-auto-m" @click="handleBtnClick(null,'delete')">
                                <Icon type="md-trash" size="17"/>删除
                            </Button>
                            <Button v-if="isProhibit" class="features-btn btn-auto-m" @click="handleBtnClick(null,'on')">
                                <Icon type="ios-unlock-outline" size="17"/>启用
                            </Button>
                            <Button v-if="isProhibit" class="features-btn btn-auto-m" @click="handleBtnClick(null,'off')">
                                <Icon type="ios-lock-outline" size="17"/>停用
                            </Button>
                        </div>
                    </div>
                    <div class="table-top-wrap-bottom">
                        <div>
                            <input type="text" class="style-input" @keyup.enter="handleSearch" v-model="search.keyword" placeholder="请输入活动名称">
                            <i-input style="display:none"></i-input>
                        </div>
                        <div>
                            <Button icon="ios-search" @click="handleSearch" class="search-btn">搜索</Button>
                        </div>
                    </div>
                </div>
            </Form>
        </global-tables>
        <Modal :mask-closable="false" v-model="isModal" :title="ModalTitle" width="600">
            <div v-if="isModal">
                <Form ref="formItem" :model="formItem" :rules="ruleValidate" :label-width="100">
                    <Row>
                        <i-col :lg="{ span: 14}">
                            <FormItem label="活动名称" prop="ActivityAName">
                                <i-input v-model="formItem.ActivityAName" placeholder="请输入活动名称"></i-input>
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col :lg="{ span:20}">
                            <FormItem label="活动类别" prop="ActivityCategory">
                                <RadioGroup v-model="formItem.ActivityCategory" @on-change="category">
                                    <Radio label="满额打折"></Radio>
                                    <Radio label="满额立减"></Radio>
                                    <Radio label="满额积分加倍"></Radio>
                                    <Radio label="满额送礼品"></Radio>
                                    <Radio label="满额免运费"></Radio>
                                </RadioGroup>
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col :lg="{ span:16}">
                            <FormItem label="消费满" prop="Consumption">
                                <i-input v-model="formItem.Consumption" placeholder="请输入金额" style="width:230px" number></i-input>&nbsp;元
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col :lg="{ span: 12}">
                            <FormItem label="折扣" prop="Discount" v-if="isDiscount">
                                <i-input v-model="formItem.Discount" placeholder="请输入折扣" value="0" style="width:230px" number :maxlength="3"></i-input>/* 例：85折请输入8.5 */
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col :lg="{ span: 20}">
                            <FormItem label="立减金额" prop="AmountReduction" v-if="isAmountReduction">
                                <i-input v-model="formItem.AmountReduction" placeholder="请输入金额" style="width:230px" number></i-input>&nbsp;元
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col :lg="{ span: 14}">
                            <FormItem label="积分" prop="Integral" v-if="isIntegral">
                                <Select v-model="formItem.Integral" style="width:230px">
                                    <Option v-for="item in integralList" :value="item.value" :key="item.value">{{ item.value }}</Option>
                                </Select>
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col :lg="{ span: 12}">
                            <FormItem label="赠送商品" prop="GiftGoods" v-if="isGiftGoods"></FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col :lg="{ span:20}">
                            <FormItem label="活动时间" prop="ActivityTime">
                                <DatePicker v-model="formItem.ActivityTime.StartTime" type="date" placeholder="开始时间" style="width:120px;margin-right:5px"></DatePicker>至
                                <DatePicker v-model="formItem.ActivityTime.EndTime" type="date" placeholder="结束时间" style="width:120px;"></DatePicker>
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col :lg="{ span: 14}">
                            <FormItem label="活动介绍地址" prop="ActiveAddress">
                                <i-input v-model="formItem.ActiveAddress" placeholder="请输入地址"></i-input>
                            </FormItem>
                        </i-col>
                    </Row>
                </Form>
            </div>
            <div slot="footer">
                <Button size="large" @click="handleClose">取消</Button>
                <Button type="primary" size="large" @click="handleSubmit('formItem')">确定</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
/**
 * 品牌列表
 */
import { cyclicRouting, getdate } from '@/util';
import { getModulePermission } from '@/api/user';
import GlobalTables from '@/components/GlobalTables';
//import AsyncSelect from '@/components/AsyncSelect';
import Api from './service';

export default {
    name: 'ProductsBrand',
    components: {
        GlobalTables
        //AsyncSelect
    },
    data() {
        // const validatorSupplierID = (rule, value, callback) => {
        //     setTimeout(() => {
        //         if (this.formItem.SupplierID == '' || !this.formItem.SupplierID) {
        //             callback(new Error('请选择所属供应商'));
        //         } else {
        //             callback();
        //         }
        //     }, 100);
        // };
        return {
            /**
             *  list 表格数据
             *  itemId 对话框id : 修改的时候需要
             *  allSelectArr 多选数据 : 批量删除或者停用
             *  loading 表格加载
             *  total 表格总页
             *  formItem 表单数据 : 提交表单对应的数据
             *  ruleValidate 表单校验
             *  isDelete 删除按钮
             *  isAddBtn 添加按钮
             *  isProhibit 停用按钮
             *  isModal 对话框状态
             *  ModalTitle  对话框标题
             *  search  请求数据 : 分页 模糊搜索
             *  columns 表头
             *  validatorSupplierID 自定义校验
             */
            list: [],
            total: 0,
            itemId: 0,
            loading: true,
            isDelete: false,
            isAddBtn: false,
            isProhibit: false,
            isModal: false,
            isDiscount: false, //折扣
            isAmountReduction: false, //立减金额
            isIntegral: false, //积分
            isGiftGoods: false, //赠送商品
            integralList: [
                //积分列表
                { value: '双倍' },
                { value: '三倍' },
                { value: '四倍' },
                { value: '五倍' }
            ],
            //startTimeOptions: {}, //开始日期设置
            //endTimeOptions: {}, //结束日期设置
            //starttime: '', //开始日期model
            //endtime: '', //结束日期model

            allSelectArr: null,
            ModalTitle: '新建品牌',
            formItem: this.initFormItem(),
            search: {
                keyword: '',
                pageindex: 1,
                pagesize: 10
            },
            ruleValidate: {
                // SupplierID: [
                //     {
                //         required: true,
                //         validator: validatorSupplierID,
                //         message: '请选择所属供应商',
                //         trigger: 'change'
                //     }
                // ],
                ActivityAName: [{ required: true, message: '请输入活动名称', trigger: 'change' }],
                Consumption: [{ required: true, type: 'number', message: '请输入金额', trigger: 'change' }], //Discount
                Discount: [{ required: true, type: 'number', message: '请输入折扣', trigger: 'change' }], //AmountReduction
                AmountReduction: [{ required: true, type: 'number', message: '请输入金额', trigger: 'change' }], //
                Integral: [{ required: true, message: '请选择积分', trigger: 'change' }], //ActivityTime
                ActivityTime: [
                    {
                        required: true,
                        message: '请选择日期',
                        trigger: 'change',
                        type: 'object',
                        fields: {
                            StartTime: { type: 'date', required: true, message: '请选择开始日期', pattern: /.+/ },
                            EndTime: { type: 'date', required: true, message: '请选择结束日期', pattern: /.+/ }
                        }
                    }
                ], //ActiveAddress
                ActiveAddress: [{ required: true, message: '请输入活动介绍地址', trigger: 'change' }]
            },
            /* 表头 */
            columns: [
                {
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    title: '活动名称',
                    key: 'ActivityAName'
                },
                {
                    title: '活动类别',
                    key: 'ActivityCategory'
                },
                {
                    title: '活动内容',
                    key: 'ActivityContent'
                },
                {
                    title: '消费金额满',
                    key: 'ConsumptionAmount'
                },
                {
                    title: '活动时间',
                    key: 'ActivityTime'
                },
                {
                    title: '状态',
                    render: (h, params) => {
                        const { IsActivity } = params.row;
                        if (IsActivity) {
                            return h('div', [
                                h('Badge', {
                                    props: {
                                        status: 'processing',
                                        text: '正常'
                                    }
                                })
                            ]);
                        } else {
                            return h('div', [
                                h('Badge', {
                                    props: {
                                        status: 'error',
                                        text: '停用'
                                    }
                                })
                            ]);
                        }
                    }
                },
                {
                    title: '操作',
                    key: 'operation'
                },
                {
                    title: '操作人',
                    key: 'Operator'
                },
                {
                    title: '操作时间',
                    width: 110,
                    key: 'OperationTime',
                    render: (h, params) => {
                        if (params.row.CreateTime) {
                            return h('div', [
                                h(
                                    'span',
                                    {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        }
                                    },
                                    getdate(new Date(params.row.CreateTime).getTime())
                                )
                            ]);
                        }
                    }
                },
                {
                    title: '操作',
                    align: 'center',
                    render: (h, params) => {
                        const { isEdit } = this;
                        return h('div', [
                            isEdit &&
                                h(
                                    'Button',
                                    {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        },
                                        style: {
                                            background: '#5ab1ef',
                                            border: 'none',
                                            marginRight: '5px'
                                        },
                                        on: {
                                            click: () => {
                                                this.handleBtnClick(params.row, 'edit');
                                            }
                                        }
                                    },
                                    '修改'
                                )
                        ]);
                    }
                }
            ]
        };
    },
    methods: {
        //判断活动类别
        category() {
            //alert(this.Discount);
            if (this.formItem.ActivityCategory == '满额打折') {
                this.isDiscount = true;
                this.isAmountReduction = false;
                this.isIntegral = false;
                this.isGiftGoods = false;
            } else if (this.formItem.ActivityCategory == '满额立减') {
                this.isDiscount = false;
                this.isAmountReduction = true;
                this.isIntegral = false;
                this.isGiftGoods = false;
            } else if (this.formItem.ActivityCategory == '满额积分加倍') {
                this.isDiscount = false;
                this.isAmountReduction = false;
                this.isIntegral = true;
                this.isGiftGoods = false;
            } else if (this.formItem.ActivityCategory == '满额送礼品') {
                this.isDiscount = false;
                this.isAmountReduction = false;
                this.isIntegral = false;
                this.isGiftGoods = true;
            } else {
                this.isDiscount = false;
                this.isAmountReduction = false;
                this.isIntegral = false;
                this.isGiftGoods = false;
            }
        },
        /* 关闭对话框 */
        handleClose() {
            this.isModal = false;
        },
        /* 提交 */
        handleSubmit(name) {
            this.$refs[name].validate(valid => {
                if (valid) {
                    let data = this.formItem;
                    Api.addTablesItem(data).then(res => {
                        if (res.state == 'success') {
                            this.$Message.success('操作成功');
                            this.loading = true;
                            this.isModal = false;
                            this.getTablesListData();
                        } else {
                            this.$Message.error(res.message);
                        }
                    });
                }
            });
        },
        /* 供应商选择 */
        setDictionaries(item, value) {
            this.formItem[value] = item.ID + ' ';
        },
        /* 表格数据请求 */
        getTablesListData() {
            const data = this.search;
            Api.getTablesList(data).then(res => {
                this.list = res.rows;
                this.loading = false;
                this.total = res.records;
            });
        },
        /* 表格查询 */
        handleSearch() {
            this.loading = true;
            this.getTablesListData();
        },
        /* 对话框 */
        handleBtnClick(item, type) {
            this.ModalTitle = '新建品牌';
            this.formItem.ActivityCategory == '满额打折';
            this.isDiscount = true;
            (this.starttime = ''), //开始日期model
                (this.endtime = ''), //结束日期model
                (this.formItem = this.initFormItem());
            if (type == 'edit' || type == 'add') {
                this.itemId = 0;
                if (type == 'edit') {
                    this.itemId = item.ID;
                    this.ModalTitle = '修改活动';
                    Api.getItemInfo({
                        keyValue: item.ID
                    }).then(res => {
                        this.isModal = true;
                        this.formItem = {
                            ...res.data,
                            SupplieerID: res.data.SupplieerID + ''
                        };
                    });
                } else {
                    this.isModal = true;
                }
            } else if (type === 'off' || type === 'on') {
                let title = '';
                if (type == 'off') {
                    title = '停用';
                } else {
                    title = '启用';
                }
                if (this.allSelectArr) {
                    this.$Modal.confirm({
                        title: `你确定要${title}吗`,
                        onOk: () => {
                            Api.setDisableEnable({
                                keyValue: this.allSelectArr,
                                value: type == 'off' ? 0 : 1
                            }).then(res => {
                                if (res.state == 'success') {
                                    this.$Message.success(res.message);
                                    this.allSelectArr = '';
                                } else {
                                    this.$Message.error(res.message);
                                }
                                this.getTablesListData();
                            });
                        },
                        onCancel: () => {
                            this.$Message.info('取消成功');
                        }
                    });
                } else {
                    this.$Message.error('请选择品牌');
                }
            } else if (type === 'delete') {
                if (this.allSelectArr) {
                    this.$Modal.confirm({
                        title: `你确定要删除吗`,
                        onOk: () => {
                            Api.deleteItem({
                                keyValue: this.allSelectArr
                            }).then(res => {
                                if (res.state == 'success') {
                                    this.$Message.success(res.message);
                                    this.allSelectArr = '';
                                } else {
                                    this.$Message.error(res.message);
                                }
                                this.getTablesListData();
                            });
                        },
                        onCancel: () => {
                            this.$Message.info('取消成功');
                        }
                    });
                } else {
                    this.$Message.error('请选择品牌');
                }
            }
        },
        /* 表单数据 */
        initFormItem() {
            return {
                SupplieerID: '',
                ActivityAName: '',
                ActivityCategory: '满额打折',
                Consumption: '',
                Discount: '',
                AmountReduction: '',
                Integral: '',
                ActivityTime: {
                    StartTime: '',
                    EndTime: ''
                },
                ActiveAddress: ''
            };
        },
        /* 表格分页方法 */
        handleChangePage(type, page) {
            this.loading = true;
            if (type == 'page') {
                this.search.pageindex = page;
                this.getTablesListData();
            } else {
                this.search.pagesizeize = page;
                this.getTablesListData();
            }
        },
        /* 复选框选中 */
        handleAllSelect(list) {
            let arr = [];
            for (let item in list) {
                arr.push(list[item].ID);
                arr.join(',');
            }
            arr = arr.join(',');
            this.allSelectArr = arr;
        }
    },
    mounted() {
        /* 获取菜单的id */
        cyclicRouting(JSON.parse(sessionStorage.getItem('user')).menuList, this.$route, id => {
            /* 按钮权限请求 */
            getModulePermission({
                roleid: JSON.parse(sessionStorage.getItem('user')).roleid,
                moduleid: id
            }).then(res => {
                /* 按钮权限赋值 */
                for (let item in res.data) {
                    if (res.data[item].name == 'add') {
                        this.isAddBtn = true;
                    } else if (res.data[item].name == 'delete') {
                        this.isDelete = true;
                    } else if (res.data[item].name == 'edit') {
                        this.isEdit = true;
                    } else if (res.data[item].name == 'onoff') {
                        this.isProhibit = true;
                    }
                }
                /* 列表请求 */
                this.getTablesListData();
            });
        });
    }
};
</script>

<style>
</style>

